﻿using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Windows.Data;
using System.Windows.Markup;

namespace Niaofei.WPF.Control
{
    public class EnumGetDescriptionConverter : MarkupExtension, IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is Enum v)
            {
                return GetDescription(v);
            }

            return string.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }

        private static string GetDescription(Enum value)
        {
            if (value != null)
            {
                var fieldInfo = value.GetType().GetField(value.ToString());
                if (fieldInfo != null)
                {
                    var attributes = fieldInfo.GetCustomAttributes<DescriptionAttribute>(inherit: false);
                    return (attributes.Count() > 0 && !string.IsNullOrEmpty(attributes.First().Description))
                        ? attributes.First().Description
                        : value.ToString();
                }
            }

            return string.Empty;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }
}
